package com.lzx.iteam.task;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.lzx.iteam.R;
import com.lzx.iteam.adapter.ContactEntryAdapter;
import com.lzx.iteam.contactssearch.ContactsDBReader;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.CcMsgStructure;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.PhoneNumberArea;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by zhangshuai on 15-5-13.
 */
public class UpLoadContactsTask extends AsyncTask<Void, Void, JSONArray> {

    private Context mContext;
    private ContactEntryAdapter mAdapter;
    private AsynHttpClient mAsynClient;
    private PreferenceUtil prefUtil;
    private HashMap<Long, String> mRegistPhone; // 注册用户的 contactId phone
    private HashMap<String, String> mUsers;  // 注册用户的 phone userId

    private static final int UPLOADPHONE = 9001;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPLOADPHONE:
                    if (msg.arg1 == 0) {

                    } else if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                        String error = mContext.getString(R.string.active_failure_no_network);
                        Toast.makeText(mContext, error, Toast.LENGTH_SHORT).show();
                    } else if (msg.obj != null) {
                        JSONObject result = (JSONObject) msg.obj;
                        try {
                            String error = result.getString(AsynHttpClient.KEY_RESULT_MSG);
                            Toast.makeText(mContext, error, Toast.LENGTH_SHORT).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toast.makeText(mContext, R.string.network_server_error,
                                Toast.LENGTH_LONG).show();
                    }
                    break;

            }
        }
    };

    public UpLoadContactsTask(Context mContext) {
        this.mContext = mContext;
        mAsynClient = AsynHttpClient.getInstance(mContext);
        prefUtil = PreferenceUtil.getInstance(mContext);
        //mRegistPhone = (HashMap<Long, String>) prefUtil.getCloudContact(PreferenceUtil.CLOUD_REGIST_USER);

        if (mRegistPhone == null) {
            mRegistPhone = new HashMap<Long, String>();
        }
        mUsers = (HashMap<String, String>) prefUtil.getCloudContact(PreferenceUtil.CLOUD_PHONE_2_USEID);
        if (mUsers == null) {
            mUsers = new HashMap<String, String>();
        }
    }

    @Override
    protected JSONArray doInBackground(Void... voids) {
        //JSONArray mPhones = getAllPhone();
        JSONArray mPhones = fillContactList();
        String sid = LocalLogin.getInstance().mSid;
        if (mPhones != null && mPhones.length() > 0 && !"AA2Fhot5Uu4AlYxYm7YRgg==".equals(sid)) {
            upLoadPhone(mPhones.toString());
        }
        return mPhones;
    }

    @Override
    protected void onPostExecute(JSONArray jsonArray) {
        super.onPostExecute(jsonArray);
        /*String sid = LocalLogin.getInstance().mSid;
        if (jsonArray != null && jsonArray.length() > 0 && !"AA2Fhot5Uu4AlYxYm7YRgg==".equals(sid)) {
            upLoadPhone(jsonArray.toString());
        }*/

    }

    public JSONArray getAllPhone() {
        JSONArray array = new JSONArray();
        Cursor cursor = null;
        Cursor phone = null;
        try {
            ContentResolver cr = mContext.getContentResolver();
            cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
                    null, null, null);
            while (cursor.moveToNext()) {

                String contactId = cursor.getString(cursor
                        .getColumnIndex(ContactsContract.Contacts._ID));
                phone = cr.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
                                + contactId, null, null);
                while (phone.moveToNext()){
                    String strPhoneNumber = phone
                            .getString(phone
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                    if (strPhoneNumber != null && !"".equals(strPhoneNumber) && (mRegistPhone.get(Long.parseLong(contactId)) == null)) {
                        array.put(strPhoneNumber);
                    }
                }
                if (phone != null) {
                    phone.close();
                }
            }
        } catch (Exception e) {
            Log.e("strPhoneNumber",e.toString());
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return array;
    }

    /**
     * 查询所有联系人
     * @return
     */
    private JSONArray fillContactList() {

        JSONArray array = new JSONArray();
        Cursor c = null;
        try {
            //: heihei the strategy of relationship sync should be confirm
            c = mContext.getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    new String[]{
                            ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                            ContactsContract.CommonDataKinds.Phone.NUMBER,
                    },
                    ContactsContract.CommonDataKinds.Phone.MIMETYPE + "='" + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
                            + "'", null, null);

            if (c != null) {
                while (c.moveToNext()) {
                    String id = String.valueOf(c.getLong(0));
                    String strPhoneNumber = PhoneNumberArea.formatNum(mContext, c.getString(2));

                    if (!StringUtil.isEmpty(strPhoneNumber)) {
                        array.put(strPhoneNumber);
                    }

                }
            }
        } finally {
            if (c != null)
                c.close();
        }
        return array;
    }


    public void upLoadPhone(String phones) {
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_PHONES, phones));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));

        UpLoadPhoneMessage message = new UpLoadPhoneMessage(mHandler.obtainMessage(UPLOADPHONE));
        message.mApi = AsynHttpClient.API_USER_SYNC_CONTACYS;
        message.mParams = mList;
        mAsynClient.execUserHttp(message);

    }

    class UpLoadPhoneMessage extends CcMsgStructure {

        private Message mmCallback;

        public UpLoadPhoneMessage(Message callback) {
            this.mmCallback = callback;
        }

        @Override
        public void onReceive(JSONObject data) {

            try {
                JSONArray result = data.getJSONArray("data");
                for (int i = 0; i < result.length(); i++) {

                    JSONObject object = (JSONObject) result.get(i);
                    String phone = object.getString("phone");
                    String uid = object.getString("user_id");
                    long contactId = ContactsDBReader.getOneContactIdByPhoneNum(mContext, phone);

                    if (mRegistPhone.get(contactId) == null) {
                        mRegistPhone.put(contactId, phone);
                    }
                    String resultPhone = "";
                    if (phone != null) {
                        resultPhone = PhoneNumberArea.formatPhoneNumDisplay(phone);
                    }
                    if (mUsers.get(resultPhone) == null) {
                        mUsers.put(resultPhone, uid);
                    }
                }
                prefUtil.saveCloudContact(PreferenceUtil.CLOUD_REGIST_USER, mRegistPhone);
                prefUtil.saveCloudContact(PreferenceUtil.CLOUD_PHONE_2_USEID, mUsers);

            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (mmCallback != null) {
                mmCallback.arg1 = 0;
                mmCallback.sendToTarget();

            }
        }

        @Override
        public void onError(int error, Object ret) {
            if (mmCallback != null) {
                mmCallback.arg1 = error;
                mmCallback.obj = ret;
                mmCallback.sendToTarget();
            }
        }
    }

}
